package com.dhcc.entity;

import java.util.HashMap;
import java.util.Map;

import com.dhcc.client.api.ApiException;
import com.dhcc.client.api.GatewayClientApi;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class AccessToken {
	private final long  SECURITY_TIME = 1800;
	private final String method = "/auth/oauth/token";
	private String chnlCode;
	private String SecretId;
	private String token;
	private long start;
	private long expires;
	private GatewayClientApi client;

	public AccessToken() {		
	}
	
	public AccessToken(GatewayClientApi client, String chnlCode, String SecretId) {
		this.chnlCode = chnlCode;
		this.SecretId = SecretId;
		this.client = client;
		this.start = this.expires = 0;
	}
	
	public String getToken() throws ApiException {
		long now = System.currentTimeMillis();
		if ((now - start) / 1000 < expires - SECURITY_TIME) {
			return token;
		}
		String httpMethod = String.format("%s?grant_type=client_credentials&client_id=%s&client_secret=%s", method, this.chnlCode, this.SecretId);
		try {
			Map<String,Object> response = client.getPublic(new HashMap<String, String>(), httpMethod);
			this.token = (String)response.get("access_token");
			if (response.get("expires_in") instanceof String) {
				this.expires = Long.parseLong((String)response.get("expires_in"));
			}else if (response.get("expires_in") instanceof Long){
				this.expires = (Long)response.get("expires_in");
			}
			
			this.start = now;
			return this.token;
			
		} catch (ApiException e) {
			e.printStackTrace();
			log.error("get token error!");
			throw e;
		}
	}
	
	
    public String getChnlCode() {
		return chnlCode;
	}

	public void setChnlCode(String chnlCode) {
		this.chnlCode = chnlCode;
	}

	public String getSecretId() {
		return SecretId;
	}

	public void setSecretId(String secretId) {
		SecretId = secretId;
	}

	public GatewayClientApi getClient() {
		return client;
	}

	public void setClient(GatewayClientApi client) {
		this.client = client;
	}

	public String getMethod() {
		return method;
	}

	public static void main(String[] args) throws ApiException {
    	GatewayClientApi client = new GatewayClientApi("http://10.2.34.22:21003");
    	AccessToken accessToken = new AccessToken(client, "C0000368-T", "1fbf338f7d654ebe82207deb8492d833");
        System.out.println("get Token: "+ accessToken.getToken());
        System.out.println("expires:" + accessToken.expires);
    }
    
    
}
